using System;
using System.Data;

namespace BRozklad.GAs
{
    [Serializable()]
    public class Population
    {
        public static DataSet rozkladDataSet;

        private static int kilkPerson = Configurations.countOfPersons;
        private Person[] persons;

        public Population(DataSet inrozklad)
        {
            persons = new Person[kilkPerson];
            rozkladDataSet = inrozklad.Copy();
        }

        public void StartGenerate()
        {
            for (int i = 0; i < kilkPerson; i++)
            {
                persons[i] = new Person();
                persons[i].StartGenerate(rozkladDataSet);
                if (notNew(i))
                    i--;
            }
            Sort();
        }

        public void NextGenerate()
        {
            Random rand = Configurations.rand;
            int halt = kilkPerson / 2;
            for (int i = halt; i < kilkPerson-1; i++)
            {
                persons[i].NextGenerate(persons[rand.Next(halt)], rozkladDataSet);
                if (notNew(i))
                    i--;
            }
            persons[kilkPerson - 1].StartGenerate(rozkladDataSet);
            Sort();

        }
        private void Sort()
        {
            int i, j, min;
            Person temppers;
            for (i = 0; i < kilkPerson; i++)
            {
                min = i;
                for (j = i + 1; j < kilkPerson; j++)
                    if (persons[min].Cost > persons[j].Cost)
                        min = j;
                if (min != i)
                {
                    temppers = persons[min];
                    persons[min] = persons[i];
                    persons[i] = temppers;
                }
            }
            int midcost = persons[kilkPerson / 2 + 1].Cost;
            if (midcost < Configurations.medianCost)
                Configurations.medianCost = midcost;
            Configurations.bestCost = persons[0].Cost;
        }


        private bool notNew(int index)
        {
            for (int i = 0; i < index; i++)
            {
                if (persons[i].GetHashCode() == persons[index].GetHashCode())
                {
                    if (persons[i].Equals(persons[index]))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /*dodatkovi*/
        public int bestCost()
        {
            Sort();
            return persons[0].Cost;
        }

        internal void SaveResult()
        {
            Sort();
            persons[0].SaveToResult();
        }
    }
}